package cn.wy.basic.interceptor;

import cn.wy.basic.jwt.JwtUtils;
import cn.wy.basic.jwt.LoginData;
import cn.wy.basic.jwt.Payload;
import cn.wy.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.security.PublicKey;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        if (token!=null) {
            String file = JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile();
            PublicKey publicKey = RsaUtils.getPublicKey(file);
            try {
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                return true;
            }catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
